'''
Author: 陈家杰-惠普 767201221@qq.com
Date: 2025-02-11 15:58:51
LastEditors: 陈家杰-惠普 767201221@qq.com
LastEditTime: 2025-02-12 10:39:58
FilePath: \陈家杰\Cloud-Computing\bash\convert_all.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
# pip install python-docx PyPDF2 python-pptx openpyxl pywin32 textract
# 把.doc、.docx、.pdf、.ppt、.pptx、.xls、.xlsx文档转换成.txt文档

import os
import docx
import PyPDF2
from pptx import Presentation
from openpyxl import load_workbook
import textract

def docx_to_txt(docx_file_path, txt_file_path):
    doc = docx.Document(docx_file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    text = '\n'.join(full_text)
    with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
        txt_file.write(text)

def pdf_to_txt(pdf_file_path, txt_file_path):
    text = ""
    with open(pdf_file_path, 'rb') as file:
        pdf_reader = PyPDF2.PdfReader(file)
        num_pages = len(pdf_reader.pages)
        for page_num in range(num_pages):
            page = pdf_reader.pages[page_num]
            text += page.extract_text()
    with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
        txt_file.write(text)

def pptx_to_txt(pptx_file_path, txt_file_path):
    prs = Presentation(pptx_file_path)
    full_text = []
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                full_text.append(shape.text)
    text = '\n'.join(full_text)
    with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
        txt_file.write(text)

def xlsx_to_txt(xlsx_file_path, txt_file_path):
    wb = load_workbook(xlsx_file_path)
    full_text = []
    for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        for row in sheet.iter_rows(values_only=True):
            row_text = '\t'.join(str(cell) if cell is not None else '' for cell in row)
            full_text.append(row_text)
    text = '\n'.join(full_text)
    with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
        txt_file.write(text)

def doc_to_txt(doc_file_path, txt_file_path):
    try:
        text = textract.process(doc_file_path).decode('utf-8')
        with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
            txt_file.write(text)
    except Exception as e:
        print(f"处理 {doc_file_path} 时出错: {e}")

def ppt_to_txt(ppt_file_path, txt_file_path):
    try:
        text = textract.process(ppt_file_path).decode('utf-8')
        with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
            txt_file.write(text)
    except Exception as e:
        print(f"处理 {ppt_file_path} 时出错: {e}")

def xls_to_txt(xls_file_path, txt_file_path):
    try:
        text = textract.process(xls_file_path).decode('utf-8')
        with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
            txt_file.write(text)
    except Exception as e:
        print(f"处理 {xls_file_path} 时出错: {e}")

def convert_files():
    file_extensions = ['.doc', '.docx', '.pdf', '.ppt', '.pptx', '.xls', '.xlsx']
    for filename in os.listdir('.'):
        file_ext = os.path.splitext(filename)[1].lower()
        if file_ext in file_extensions:
            input_file = filename
            output_file = os.path.splitext(input_file)[0] + '.txt'
            if file_ext == '.docx':
                docx_to_txt(input_file, output_file)
            elif file_ext == '.pdf':
                pdf_to_txt(input_file, output_file)
            elif file_ext == '.pptx':
                pptx_to_txt(input_file, output_file)
            elif file_ext == '.xlsx':
                xlsx_to_txt(input_file, output_file)
            elif file_ext == '.doc':
                doc_to_txt(input_file, output_file)
            elif file_ext == '.ppt':
                ppt_to_txt(input_file, output_file)
            elif file_ext == '.xls':
                xls_to_txt(input_file, output_file)
            print(f"已将 {input_file} 转换为 {output_file}")

if __name__ == "__main__":
    convert_files()